import React, {useEffect, useState} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import AreaView from '../../components/Layout/AreaView';
import XPay from 'react-native-puti-pay';
import {getUserProfile} from '../../service/user';
import {launchImageLibrary} from 'react-native-image-picker';
import styles from './style';
import {
  Icon,
  TextareaItem,
  InputItem,
  List,
  Toast,
  Picker,
} from '@ant-design/react-native';
import {createOrder, alipayAppPay} from '../../service/home';
import {getTeacher, reviewUpload, contentReview} from '../../service/common';

const ReadingProblem = () => {
  const navigation = useNavigation();
  const [list, setList] = useState([]);
  const [teacher, setTeacher] = useState();
  const [ques, setQues] = useState('');
  const [imgList, setImgList] = useState([]);
  const [title, setTitle] = useState('');
  const [userProfileData, setUserProfileData] = useState({});
  useEffect(() => {
    // //设置    支付宝URL Schemes
    XPay.setAlipayScheme('alipay');
    getUserProfile().then((res) => {
      console.log(res.data);
      setUserProfileData(res.data);
    });
  }, []);
  useEffect(() => {
    navigation.setOptions({
      title: '阅片服务',
      // headerRight: () => <SearchHeadIcon />,
    });
    getTeacher().then((res) => {
      if (res.code == 200) {
        const _list = res.data.map((item) => ({
          ...item,
          value: item.custId,
          label: item.custName,
        }));
        setList(_list);
      }
    });
  }, [navigation]);
  const submit = () => {
    if (ques && teacher && imgList.length && imgList.length > 0) {
      createOrder({
        actualPrice: imgList.length * 0.01,
        couponId: '',
        couponName: '',
        createBy: userProfileData?.createBy,
        custAddress: '',
        custId: userProfileData?.custId,
        custName: userProfileData?.custName,
        freePrice: 0,
        isReceipt: 0,
        orderChannels: 1,
        orderId: null,
        orderNo: null,
        orderStatus: 0,
        orderType: 2,
        revision: 1,
        smOrderCmCourseList: [],
        totalPrice: 0,
        receipt: {
          accountNumber: '',
          bankName: '',
          cardCode: '',
          headName: '',
          headType: 1,
          receiptDesc: 1,
          receiptKind: 1,
          unitAddress: '',
          unitPhone: '',
        },
      }).then((res) => {
        console.log(res);
        if (res.code === 200) {
          alipayAppPay({
            amt: imgList.length * 0.01,
            billNo: res?.data?.orderNo,
            body: title,
            payType: '3',
            subject: '阅片付款',
          }).then((orderRes) => {
            //支付宝支付
            XPay.alipay(orderRes.msg, (result) => {
              console.log(result, 'result');
              if (result.resultStatus === '9000') {
                contentReview({
                  price: imgList.length * 0.01,
                  reviewContent: ques,
                  reviewImage: imgList?.map(s => s.imgId).join('|'),
                  reviewTitle: title,
                  reviewType: 0,
                  teacherId: teacher[0],
                }).then((_res) => {
                  console.log(_res);
                  _res.code === 200 && navigation.replace('Reading');
                });
              } else {
                Toast.fail('支付失败', 2);
              }
            });
          });
        }
      });
    } else {
      Toast.info('请输入阅片信息');
    }
  };
  return (
    <AreaView>
      {/* <View style={styles.wrapper_container}>
        <View style={styles.img_container}>
          <Text>1</Text>
        </View>
      </View> */}
      <View style={styles.questiond_content}>
        <View style={styles.title_container}>
          <Text style={styles.title}>提问</Text>
        </View>
        <View style={styles.input_container}>
          <TextareaItem
            style={styles.textarea}
            rows={4}
            placeholder="请输入您的问题..."
            onChangeText={(val) => setQues(val)}
          />
          <View style={styles.upload_container}>
            <TouchableOpacity
              activeOpacity={1}
              style={styles.upload}
              onPress={() => {
                launchImageLibrary(
                  {
                    mediaType: 'photo',
                    includeBase64: false,
                  },
                  (response) => {
                    const file = {
                      uri: response.uri,
                      name: response.fileName,
                      type: 'multipart/form-data',
                    };
                    let formData = new FormData();
                    formData.append('file', file);
                    console.log('formdata', JSON.stringify(formData));
                    reviewUpload(formData).then((res) => {
                      console.log(res);
                      if (res.code === 200) {
                        imgList.push(res);
                        setImgList([...imgList]);
                      }
                    });
                  },
                );
              }}>
              <Icon name="file-image" />
              <Text style={styles.upload_text}>点击添加照片</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.upload_list_container}>
            {imgList.map((item, index) => (
              <View key={item + index} style={styles.upload_list}>
                <Text numberOfLines={1} style={styles.upload_name}>
                  {item.imgName}
                </Text>
                <TouchableOpacity
                  onPress={() => {
                    imgList?.splice(index, 1);
                    setImgList([...imgList]);
                  }}>
                  <Text style={styles.upload_btn}>删除</Text>
                </TouchableOpacity>
              </View>
            ))}
          </View>
        </View>
        <View style={styles.title_teach_container}>
          <InputItem
            style={styles.input_font}
            clear
            labelNumber={4}
            placeholder="请输入您的标题"
            onChangeText={(val) => setTitle(val)}>
            <Text style={styles.input_text}>标题</Text>
          </InputItem>
          <Picker
            data={list}
            cols={1}
            value={teacher}
            onChange={(val) => setTeacher(val)}>
            <List.Item>
              <Text style={styles.list_text}>选择老师</Text>
            </List.Item>
          </Picker>
        </View>
        <View style={styles.problem_money}>
          <Text style={styles.problem_money_text}>
            本次咨询需要支付：￥{imgList.length * 0.01}
          </Text>
        </View>
        <View style={styles.btn_container}>
          <TouchableOpacity  activeOpacity={1} style={styles.btn} onPress={submit}>
            <Text style={styles.btn_text}>支付并提交件</Text>
          </TouchableOpacity>
        </View>
      </View>
    </AreaView>
  );
};

export default ReadingProblem;
